package com.huawei.boss.resources;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.sql.Timestamp;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.Assert;

import freemarker.cache.TemplateLoader;

public class DatabaseTemplateLoader implements TemplateLoader
{
    private JdbcTemplate jdbcTemplate;
   
    public void setDataSource(DataSource dataSource)
    {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }
   
    /**
     * {@inheritDoc}
     */
    public void closeTemplateSource(Object templateSource) throws IOException
    {
        // noting to do with jdbcTemplate
    }
   
    /**
     * 根据模板标识获取模板资源对象
     *
     * @param name 模板标识
     * @return 有相应模板资源对象则返回
     */
    public Object findTemplateSource(String name) throws IOException
    {
        Assert.notNull(name);
        return name;
    }
   
    /**
     * 返回模板资源最新修改时间值
     *
     * @param templateSource 模板资源对象
     * @return 返回最新修改时间
     */
    public long getLastModified(Object templateSource)
    {
        Assert.isInstanceOf(String.class, templateSource);
        Timestamp timestamp = (Timestamp) this.jdbcTemplate.queryForObject("select updatetime from sa_db_script where scriptid = ?",
                new Object[] { (String) templateSource },
                Timestamp.class);
        return timestamp.getTime();
    }
   
    /**
     * {@inheritDoc}
     */
    public Reader getReader(Object templateSource, String encoding) throws IOException
    {
        Assert.isInstanceOf(String.class, templateSource);
       
        String source = (String) jdbcTemplate.queryForObject("select scriptsource from sa_db_script where scriptid = ?",
                new Object[] { (String) templateSource },
                String.class);
        return new StringReader(source);
    }
}